'use strict';
const fiip = require('fiip');
const Format = fiip.Format;

class StdpFormat extends Format {
  constructor(lenMax) {
    super(lenMax);
    this.msg = {
      leading: this.buf.slice(0, 3), //前导
      startTag: this.buf.slice(3, 5), //起始标识
      srcAddr: this.buf.slice(5, 13), //源地址
      dstAddr: this.buf.slice(13, 21), //目标地址
      ttl: this.buf.slice(21, 22), //生存时间
      type: this.buf.slice(22, 23), //协议类型
      version: this.buf.slice(23, 24), //stdp版本号
      control: this.buf.slice(24, 25), //控制字段
      reserve1: this.buf.slice(25, 28), //预留1
      cmd: this.buf.slice(28, 30), //命令标识
      index: this.buf.slice(30, 32), //命令序列号
      len: this.buf.slice(32, 34), //消息体长度
      body: this.buf.slice(34, this.bufLenMax - 7), //消息体
      crc: this.buf.slice(this.bufLenMax - 7, this.bufLenMax - 5), // CRC校验
      endTag: this.buf.slice(this.bufLenMax - 5, this.bufLenMax - 3), //结束标识
      trailing: this.buf.slice(this.bufLenMax - 3, this.bufLenMax), //后继
    };
    Object.freeze(this.msg);
    this.msg.type[0] = this.type;
    this.msg.version[0] = this.version;
    this._index = [0x00, 0x01];
  }

  setVar(field, data, dataLen) {
    if (field == 'body') {
      //设置指令序列号index
      if (this._index[1] == 0xff) {
        this._index[0]++;
        this._index[1] = 0x00;
      } else {
        this._index[1]++;
      }
      this.msg['index'][0] = this._index[0];
      this.msg['index'][1] = this._index[1];

      //设置消息体长度
      this.msg['len'][0] = dataLen >> 8;
      this.msg['len'][1] = dataLen;
      this.bufLen = 34 + dataLen;
    }
    for (let i = 0; i < dataLen; i++) {
      this.msg[field][i] = data[i];
    }
  }
  getMsg() {
    let msg = super.getMsg();
    if (msg) {
      msg.version = msg.body.slice(0, 1);
      msg.control = msg.body.slice(1, 2);
      msg.reserve1 = msg.body.slice(2, 5);
      msg.cmd = msg.body.slice(5, 7);
      msg.index = msg.body.slice(7, 9);
      msg.len = msg.body.slice(9, 11);
      msg.body = msg.body.slice(11);
      return msg;
    } else {
      return null;
    }
  }
  respond(msg, error, body) {
    let msg_body = Buffer.concat(body ? [msg.index, error, body] : [msg.index, error]);
    let msg_cmd = Buffer.from(msg.cmd);
    msg_cmd[0] = msg_cmd[0] | 0x80;
    this.setVar('cmd', msg_cmd, 2);
    this.setVar('body', msg_body, msg_body.length);
    fiip.send(this, msg.srcAddr, null);
  }
}
StdpFormat.prototype.type = 0x00;
StdpFormat.prototype.version = 0x02;
StdpFormat.type = 0x00;
StdpFormat.version = 0x02;

module.exports = StdpFormat;
